package com.android.interfata;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ParseException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableLayout.LayoutParams;
import android.widget.TableRow;
import android.widget.TextView;

public class Product1 extends Activity implements OnRatingBarChangeListener, Runnable 
{
	private static final String TAG = "Interfata 09";
	private int contorDescription = 0, contorRetailers = 0, contorStatistics = 0;
	private String urlDefault = "http://mail.pioneerinvestments.ro:333/images/img.jpg";

	private String linkAmazon, linkEbay;
	private Long idProduct;
	private Double priceEbay = 0.0, priceAmazon = 0.0 , price = 0.0;
	
	private Boolean threadPrice = false, threadDescription = false, threadRating = false;
	private Boolean esteLaBookmark = false,  esteLaSubscribe = false;
	
	private String description = "";
	private Double rating = 0.0, ratingAvg = 0.0;
	
	private String user, pass, urlStatistics;
	private int userId;
	
	public static Double priceAlarm = 0.0;
	public static Double procentAlarm = 0.0;
	
	public static Boolean pricePus = false, procentPus = false;
	
	private static int scrWidth, scrHeight; 
		
    private ProgressDialog pd;
	boolean primaData = true;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		try
		{
			super.onCreate(savedInstanceState); 
			setContentView(R.layout.product1);
			
			SharedPreferences logPref = getSharedPreferences("LoginPref", MODE_PRIVATE);
			
			/* username si logout din heade - le completez cu datele corespunzatoare */
	        TextView userheader = (TextView) findViewById(R.id.userHeader);
	        String username = logPref.getString("user", "username");
	        userheader.setText(username);		
	    	
	        TextView logout = (TextView) findViewById(R.id.logoutHeader);
			/**** delogare ****/
			logout = (TextView) findViewById(R.id.logoutHeader);
			logout.setOnClickListener(new View.OnClickListener() 
			{
	            public void onClick(View v) 
	            {
	            	askOK();
	            }
	        });
			/**** end delogare ****/
			
			
			
	    	user = logPref.getString("user", "user");
	    	pass = logPref.getString("pass", "pass");
	    	userId = logPref.getInt("ID", 0);
			System.out.println(user + " " + pass + " " + userId);
			System.out.println("Price Procent2: " + priceAlarm + " " + procentAlarm);
			
			Intent i = getIntent();
	 		
			idProduct = i.getLongExtra("id", 0);
			
			
			//pd = ProgressDialog.show(this, "Working..", "Loading data", true, false);
			
			pd = new ProgressDialog(this);
			pd.setIndeterminate(true);
			pd.setIndeterminateDrawable(getResources().getDrawable(R.anim.loading_anim));
			pd.setMessage("Loading data. Please wait");
			//pd.setTitle("Cotrobaing...");
			pd.setCancelable(false);
			pd.show();
			
			Thread thread = new Thread(this);
			thread.start();
			
		
		            

     	}
 		catch(Exception e)
     	{
     		System.out.println("Errrr Product " + e.getMessage());
     	}
     }
	
	


	
/*----------------------------------loading----------------------------------------*/
	
	protected void onResume()
	{

		super.onResume();  //The activity is about to become visible.
		if (primaData == false && procentPus == false && pricePus == false)
		{
			/*
			
			Log.d("book", "resume" + primaData);
			pd = ProgressDialog.show(this, "Working..", "Loading data", true, false);
	
			Thread thread = new Thread(this);
			thread.start();
			*/
			
		}
		else
		{
			primaData = false;
		}
		
		
		if (procentAlarm != 0.0 && procentPus == true)
		{
			procentPus = false;
			addProductAlarmProcent();
			
			ImageView subs = (ImageView) findViewById(R.id.subscribe_produs_image);					
			subs.setImageResource(R.drawable.subscribe_produs_lista);
			
		}
		if (priceAlarm != 0.0 && pricePus == true)
		{
			pricePus = false;
			addProductAlarmPrice();
			
			ImageView subs = (ImageView) findViewById(R.id.subscribe_produs_image);					
			subs.setImageResource(R.drawable.subscribe_produs_lista);
			
		}
		
        System.out.println("Price Procent12 : " + priceAlarm + " " + procentAlarm);
	}
	

    public void run() 
    {
            //pi_string = Pi.computePi(800).toString()
    	try 
		{
    		init();
	
		} 
		catch (ParseException e) 
		{
			e.printStackTrace();
		}
        
		handler.sendEmptyMessage(0);
    }

    private Handler handler = new Handler()
    {
            @Override
            public void handleMessage(Message msg) 
            {
                pd.dismiss();
                //tv.setText(pi_string);*/
                try
                {
                
                	setInfo();
    	          	allKindOfButtons();
                	makeVisible();
        			
                }
		    	catch( Exception e)
		    	{
		    		Log.d("err - handle populare", "err" + e.getLocalizedMessage());
		    	}
            }
    };
	
	
	
	/*----------------------------------end loading----------------------------------------*/
    
    
    private void makeVisible()
    {
    	TextView nume = (TextView)findViewById(R.id.nameText1);
    	nume.setVisibility(View.VISIBLE);
    	
    	FrameLayout fl = (FrameLayout)findViewById(R.id.frame_layout);
    	fl.setVisibility(View.VISIBLE);
    	
    	ScrollView sc = (ScrollView)findViewById(R.id.sv_product);
    	sc.setVisibility(View.VISIBLE);
    	
    }
	
	private void allKindOfButtons()
	{
		try
		{
			   Log.d(TAG, "allKindOfButtons()");
    	        
		        /*----------------------------------	Buttons	  ------------------------------------------------*/
		        
		        
		        final RatingBar ratingbar = (RatingBar) findViewById(R.id.my_rating_bar);
		        ratingbar.setOnRatingBarChangeListener(this);
		        ratingbar.setRating(rating.floatValue());
		        
		        
		    	
		    	
		    	
		        
		        /*--------------------- Bookmark Subscribe -----------------------------*/
		        
		       
		         
		        ImageView bookmarkIB = (ImageView) findViewById(R.id.bookmark_produs_image);
		        if (esteLaBookmark == false)
		        {
		        	 bookmarkIB.setImageResource(R.drawable.bookmark_produs_nu);
		        	 bookmarkIB.setOnClickListener(new View.OnClickListener()
		 	        {				
		 				public void onClick(View v) 
		 				{
		 										
		 					ImageView book = (ImageView) findViewById(R.id.bookmark_produs_image);					
		 					book.setImageResource(R.drawable.bookmark_produs_lista);
		 					addProductToBookmark();
		 					
		 										
		 				}
		 			});
		        }	
		        	
		       
		
		        ImageView subscribe = ( ImageView) findViewById(R.id.subscribe_produs_image);
				if (esteLaSubscribe == false)
		        {
					subscribe.setImageResource(R.drawable.subscribe_produs_nu);
			        subscribe.setOnClickListener(new View.OnClickListener()
			        {				
						public void onClick(View v) 
						{
							// Il adaugam in lista de subscribe
							
							//ImageButton subs = (ImageButton) findViewById(R.id.subscribe_produs_image);					
							//subs.setImageResource(R.drawable.bookmark_produs_lista);
							
							Intent intent = new Intent(getApplicationContext(), AddProductAlarm.class);
							startActivity(intent);
							System.out.println("Price Procent: " + priceAlarm + " " + procentAlarm);
						
							
												
						}
						
						
					});
				
			        System.out.println("Price Procent4 zum: " + priceAlarm + " " + procentAlarm);

		        }        
				
				System.out.println("Price Procent3: " + priceAlarm + " " + procentAlarm);
		        Log.d(TAG, "din Product D R S");
		     	        
		     	        
		        /*--------------------- Description Retailers Statistics  --------------*/
		        
		     
												
					ImageView more = (ImageView) findViewById(R.id.more_description);
					more.setOnClickListener(new View.OnClickListener()
			        {				
						public void onClick(View v) 
						{
							Intent intent = new Intent(getApplicationContext(), Description.class);
							intent.putExtra("description",  description);
							startActivity(intent);
							
						}
					});
					        
				
					ImageView statistics = (ImageView) findViewById(R.id.statistics_image1);
                    statistics.setOnClickListener(new View.OnClickListener()
                    {                                
                            public void onClick(View v) 
                            {
                                    if ( urlStatistics.equals("") == false)
                                    {
                                            Intent i = getIntent();
                                            String prod = i.getStringExtra("product");
                                            Intent intent = new Intent(getApplicationContext(), Statistics.class);
                                            intent.putExtra("url", urlStatistics);
                                            intent.putExtra("prodTitle", prod);
                                            startActivity(intent);
                                    }
                                    else
                                    {
                                            wariningStatistics();
                                            
                                    }
                                    
                            }
                    });

			    				
					
											
					
						showRetailers();		            
	             

         	}
     		catch(Exception e)
         	{
         		System.out.println("Errrr Product " + e.getMessage());
         	}
	}
	
	private void wariningStatistics()
	{
		System.out.println("wariningStatistics()");
		AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
		dlgAlert.setMessage("We don't have statistics for this product");
        dlgAlert.setTitle("Warning");
        dlgAlert.setPositiveButton("OK", null);
        dlgAlert.setCancelable(true);
        dlgAlert.create().show();
		
	}
	
	 public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser)
	 {
		  Boolean ok;
		  System.out.println("Rating is " + rating);  
		  try
    	  {
			    int r = (int)rating;
		    	String xml = XMLfunctions.getXML("AddRating?UserID=" + userId + "&UserUsername=" + user + "&Password=" + pass +"&ProductID=" + idProduct.toString()+ "&value=" + Integer.toString(r));
	    	
		    	
		        Document doc = XMLfunctions.XMLfromString(xml);
		        
		        NodeList nodes = doc.getElementsByTagName("Mesaje");
		        System.out.println(nodes.getLength());		
		        
				for (int i = 0; i < nodes.getLength(); i++)
				{							
									
					Element e = (Element)nodes.item(i);
					ok = Boolean.parseBoolean(XMLfunctions.getValue(e, "Success"));
					System.out.println("onRatingChanged " + ok );
								
				}
				TextView ratingValue= (TextView) findViewById(R.id.ratingValue);
		 		ratingValue.setText(ratingAvg.toString());
			
	    	}
	    	catch(Exception e)
	    	{
	    		System.out.println("din thread Bookmark" + e);
	    	}
			
		  
	 }
		 
	
	
	
	public final static void setPriceAlarm(Double p)
	{
		priceAlarm = p;
		
        System.out.println("Price Procent45 zum: " + priceAlarm + " " + procentAlarm);
	}

	public final static void setProcentAlarm(Double p)
	{
		procentAlarm = p;
		
        System.out.println("Price Procent44 zum: " + priceAlarm + " " + procentAlarm);
	}

	
	
	
	
/*--------------------------------------------------Initializari--------------------------------------------------------*/
	
	public void init()
 	{
		Intent i = getIntent();
 		
		idProduct = i.getLongExtra("id", 0);
 	
	    getPrices();
	    getDescription();
 		 		
 		getProductRating();
 		
 		System.out.println("rating" + rating);
 				 		
 		
 		//vedem daca produsul e sau nu adaugat la Bookmark/Subscribe
 		
 		getProductBookmark();
 		getProductSubscribe();
 	       
        /*---------------Poza de la staistici--------------*/
        
        getPictureStatistics();
      
 	}
	
	
	
	private void setInfo()
	{
		
		System.out.println("inceput setInfo Product");
 		Intent i = getIntent();
 	
 		idProduct = i.getLongExtra("id", 0);
 		
		System.out.println("Bla Product");
 		
 		//Rating
 		
 	//	ratingAvg = i.getDoubleExtra("rating", 0.0);
 		
 		System.out.println("ratingAvg" + ratingAvg);
 		
 		TextView ratingValue= (TextView) findViewById(R.id.ratingValue);
 		ratingValue.setText(ratingAvg.toString());
 		
		
		price = i.getDoubleExtra("price", 0.0);
 		TextView priceProduct = (TextView) findViewById(R.id.priceProduct);
 		priceProduct.setText(price.toString() + " $");
	        
	    //pun numele pe care il iau din lista
 		
		TextView txtProduct = (TextView) findViewById(R.id.nameText1);        
        String name = i.getStringExtra("product");
        txtProduct.setText(name);
		System.out.println("inceput " + name);
		
        TextView txtCategory = (TextView) findViewById(R.id.info_cat1);        
        String category = i.getStringExtra("category");
        txtCategory.setText(category);
        
            
        TextView txtBrand = (TextView) findViewById(R.id.info_cat2);        
        String brand = i.getStringExtra("brand");
        txtBrand.setText(brand);
                       
        linkEbay = i.getStringExtra("linkEbay");
        linkAmazon = i.getStringExtra("linkAmazon");
        
        
        System.out.println("Amazon " + linkAmazon);	
        System.out.println("Ebay" + linkEbay + "hhh");
		
		 
        /*-----------------Autori----------*/
        String authors = i.getStringExtra("authors");
        TableRow tra = (TableRow)findViewById(R.id.info3);
        if (authors.equals("") == false)
        {        
	        TextView txtAuthors = (TextView) findViewById(R.id.info_cat3);        
	        txtAuthors.setText(authors);
        }
        else
        {
        	tra.setVisibility(View.GONE);
        }

        
		// preiau dimensiunile ecranului
 		
		Display display = getWindowManager().getDefaultDisplay(); 
		scrWidth = (int)display.getWidth();  // deprecated
		scrHeight = (int)display.getHeight();  // deprecated
		
		// incarc poza
		
		String url = i.getStringExtra("imageLarge");
		if ( url.equals("") == true)
			url = urlDefault;
		
		Drawable image = ImageOperations(getApplicationContext(), url, "image.jpg");
		System.out.println("Bla4 Product");
		// dimensiunile pozei
		
		int imgHeight = (int)(image.getIntrinsicHeight());
		int imgWeight = (int)image.getIntrinsicWidth();
	
		
		System.out.println("----------------------Padding   Screnn: " + (scrWidth-80) + imgWeight );
		
		
        // redimensionez poza
		image = resize(image, scrWidth, scrHeight, imgHeight, imgWeight);
		System.out.println("Bla2 Product");
		ImageView img = (ImageView) findViewById(R.id.productImg1);
        img.setImageDrawable(image);
		
	}
	
	/*-------------------------------------------Poza de la staistici---------------------------------------------*/	
	
	private void getPictureStatistics()
	{
		try
    	{
			urlStatistics = XMLfunctions.getStatistics("http://mail.pioneerinvestments.ro:333/UserControl/Statistici.aspx?ProductID="+ idProduct.toString() );
    	  
			/*
			 * 
			 * 
			Display display = getWindowManager().getDefaultDisplay(); 
			int scrWidth = (int)display.getWidth();  // deprecated
			int scrHeight = (int)display.getHeight();  // deprecated
			Drawable image = ImageOperations(getApplicationContext(), url, "image.jpg");
			
			// dimensiunile pozei
			
			int imgHeight = (int)(image.getIntrinsicHeight());
			int imgWeight = (int)image.getIntrinsicWidth();
			
	        // redimensionez poza
			image = resize2(image, scrWidth, scrHeight, imgHeight, imgWeight);
		
			ImageView img = (ImageView) findViewById(R.id.statistics_image1);
	        img.setImageDrawable(image);
	       */
		
    	}
    	catch(Exception e)
    	{
    		System.out.println("getPictureStatistics()" + e);
    	}
		
	}

/*--------------------------------------------------Add Bookmark/Subscribe-----------------------------------------*/

	private void addProductToBookmark()
	{
		try
    	{
	    	String xml = XMLfunctions.getXML("AddBookmark?UserID=" + userId + "&UserUsername=" + user + "&Password=" + pass +"&ProductID=" + idProduct.toString());
    	
	    	
	        Document doc = XMLfunctions.XMLfromString(xml);
	        
	        NodeList nodes = doc.getElementsByTagName("AddBookmarkResult");
	        System.out.println(nodes.getLength());		
	        
			for (int i = 0; i < nodes.getLength(); i++)
			{							
								
				Element e = (Element)nodes.item(i);
				esteLaBookmark = Boolean.parseBoolean(XMLfunctions.getValue(e, "Success"));
				System.out.println("esteLaBookmark " + esteLaBookmark );
							
			}	
		
    	}
    	catch(Exception e)
    	{
    		System.out.println("din thread Bookmark" + e);
    	}
		
	}
	
		
	
	private void addProductAlarmProcent()
	{
		try
    	{
			String xml = XMLfunctions.getXML("AddAlarmProcent?UserID=" + userId + "&UserUsername=" + user + "&Password=" + pass +"&ProductID=" + idProduct.toString()+ "&Percent=" + procentAlarm.toString() );
			System.out.println("aPAProcent " + xml);	  	    	
	        Document doc = XMLfunctions.XMLfromString(xml);
	        
	        NodeList nodes = doc.getElementsByTagName("Mesaje");
	        System.out.println(nodes.getLength());		
	        
			for (int i = 0; i < nodes.getLength(); i++)
			{							
								
				Element e = (Element)nodes.item(i);
				esteLaSubscribe = Boolean.parseBoolean(XMLfunctions.getValue(e, "Success"));
				System.out.println("esteLaSubscribe " + esteLaSubscribe );
							
			}	
		
    	}
    	catch(Exception e)
    	{
    		System.out.println("din addProductAlarmProcent()" + e);
    	}
		
	}
	
	
	private void addProductAlarmPrice()
	{
		try
    	{
			String xml = XMLfunctions.getXML("AddAlarmPrice?UserID=" + userId + "&UserUsername=" + user + "&Password=" + pass +"&ProductID=" + idProduct.toString()+ "&AlertPrice=" + priceAlarm.toString());
	    	System.out.println("aPAPrice " + xml);	    	
	        Document doc = XMLfunctions.XMLfromString(xml);
	        
	        NodeList nodes = doc.getElementsByTagName("Mesaje");
	        System.out.println(nodes.getLength());		
	        
			for (int i = 0; i < nodes.getLength(); i++)
			{							
								
				Element e = (Element)nodes.item(i);
				esteLaSubscribe = Boolean.parseBoolean(XMLfunctions.getValue(e, "Success"));
				System.out.println("esteLaSubscribe " + esteLaSubscribe );
							
			}	
		
    	}
    	catch(Exception e)
    	{
    		System.out.println("din addProductAlarmPrice()" + e);
    	}
		
	}
	
	
/*--------------------------------------------------Threds--------------------------------------------------------*/
	
	private void getPrices()
	{
		
    	Double pret;
    	String siteName;
    	
    	System.out.println("getPrices()1");
    	try
    	{
	    	String xml = XMLfunctions.getXML("GetProductPriceBest?ProductID=" + idProduct.toString() );
	    	

	        System.out.println("getPrices()11");
	        Document doc = XMLfunctions.XMLfromString(xml);
	        
	        System.out.println("getPrices()2");
	        
	        NodeList nodes = doc.getElementsByTagName("TipPreturi");
	        System.out.println(nodes.getLength());		
	        
	        System.out.println("getPrices()3");
	        
			for (int i = 0; i < nodes.getLength(); i++)
			{							
								
				Element e = (Element)nodes.item(i);
				pret = Double.parseDouble(XMLfunctions.getValue(e, "Pret"));
				siteName = XMLfunctions.getValue(e, "SiteName");
							
				System.out.println("getPrices()4");
				
				if (siteName.equals("Amazon") == true )
				{
					priceAmazon = pret;
					System.out.println("priceAmazon " + priceAmazon);
				}	
				else
				{
					priceEbay = pret;
					
					System.out.println("priceEbay " + priceEbay);
				}
						
					
			}	
			
			System.out.println("getPrices()5");
		
    	}
    	catch(Exception e)
    	{
    		System.out.println("din thread getPrice" + e);
    	}
		    
		
	}
	
	
	private void getRatingAvg()
	{
		
    	
    	try
    	{
	    	String xml = XMLfunctions.getXML("GetProdusByID?ProdusID=" + idProduct.toString() );
	    			
	        Document doc = XMLfunctions.XMLfromString(xml);
	        
	        NodeList nodes = doc.getElementsByTagName("TipProdus");
	        System.out.println(nodes.getLength());		
	        
			for (int i = 0; i < nodes.getLength(); i++)
			{							
								
				Element e = (Element)nodes.item(i);
				ratingAvg = Double.parseDouble(XMLfunctions.getValue(e, "Rating"));
				System.out.println("getRatingAvg() " + ratingAvg);
							
			}	
		
    	}
    	catch(Exception e)
    	{
    		System.out.println("din getRatingAvg()" + e);
    	}

	}
	
	private void getDescription()
	{
		
    	try
    	{
	    	String xml = XMLfunctions.getXML("GetProdusByID?ProdusID=" + idProduct.toString() );
	    	System.out.println("Desc " + xml);
			//Nu imi ia toata descrierea
	        Document doc = XMLfunctions.XMLfromString(xml);
	        
	        NodeList nodes = doc.getElementsByTagName("TipProdus");
	        System.out.println(nodes.getLength());		
	        
			for (int i = 0; i < nodes.getLength(); i++)
			{							
								
				Element e = (Element)nodes.item(i);
				description = XMLfunctions.getValue(e, "description");
				System.out.println("Desc " + description);
				
				ratingAvg = Double.parseDouble(XMLfunctions.getValue(e, "Rating"));
				System.out.println("RatingAvg " + ratingAvg);
							
			}	
		
    	}
    	catch(Exception e)
    	{
    		System.out.println("din thread Description" + e);
    	}
		
	}
		
	
	private void getProductRating()
	{
		
		
    	try
    	{
	    	String xml = XMLfunctions.getXML("GetUserRating?UserID=" + userId + "&UserUsername=" + user + "&Password=" + pass +"&ProductID=" + idProduct.toString());
    		
	    	System.out.println("getProductRating " + xml);
			
	        Document doc = XMLfunctions.XMLfromString(xml);
	        
	        NodeList nodes = doc.getElementsByTagName("MesajeRatings");
	        System.out.println(nodes.getLength());		
	        
			for (int i = 0; i < nodes.getLength(); i++)
			{							
								
				Element e = (Element)nodes.item(i);
				rating = Double.parseDouble(XMLfunctions.getValue(e, "rating"));
				System.out.println("rating " + rating );
							
			}	
		
    	}
    	catch(Exception e)
    	{
    		System.out.println("din thread Description" + e);
    	}
		
		
	}
	
	private void getProductBookmark()
	{
		
		
    	try
    	{
    		String xml = XMLfunctions.getXML("GetUserBookmark?UserID=" + userId + "&UserUsername=" + user + "&Password=" + pass +"&ProductID=" + idProduct.toString());
        	System.out.println("Bookmark " + xml);
	        Document doc = XMLfunctions.XMLfromString(xml);
	        
	        NodeList nodes = doc.getElementsByTagName("Mesaje");
	        System.out.println("Noudri din Bookmark " + nodes.getLength());		
	        
			for (int i = 0; i < nodes.getLength(); i++)
			{							
								
				Element e = (Element)nodes.item(i);
				esteLaBookmark = Boolean.parseBoolean(XMLfunctions.getValue(e, "Success"));
				System.out.println("esteLaBookmark " + esteLaBookmark );
							
			}	
		
    	}
    	catch(Exception e)
    	{
    		System.out.println("1 din thread Bookmark  " + e);
    	}

		
	
	}
	
	
	private void getProductSubscribe()
	{
		
	
    	try
    	{
	    
    		String xml = XMLfunctions.getXML("GetUserAlarm?UserID=" + userId + "&UserUsername=" + user + "&Password=" + pass +"&ProductID=" + idProduct.toString());
    		System.out.println("Alarm " + xml);
	        Document doc = XMLfunctions.XMLfromString(xml);
	        
	        NodeList nodes = doc.getElementsByTagName("Mesaje");
	        System.out.println(nodes.getLength());		
	        
			for (int i = 0; i < nodes.getLength(); i++)
			{							
								
				Element e = (Element)nodes.item(i);
				esteLaSubscribe = Boolean.parseBoolean(XMLfunctions.getValue(e, "Success"));
				System.out.println("esteLaSubscribe " + esteLaSubscribe );
							
			}	
		
    	}
    	catch(Exception e)
    	{
    		System.out.println("2 din thread Subscribe" + e);
    	}
	
	
	}
	
/*--------------------------------------------------Retailers--------------------------------------------------------*/

     	private void showRetailers()
     	{
     		int num = 1, width;
     		    		
     		
     		try
     		{
     			if ( linkAmazon.equals("") != true)
     				num++;
     			
     			if ( linkEbay.equals("") != true)
     				num++;
     			
     			width = (scrWidth - 20*num) / num;
     			
     			System.out.println("showRetailerssasadssadasd" + num + " " + priceAmazon + " " + priceEbay);
     			
     		
     			
	     		// In functie de ce informatii avem afisam furnizorii corespunzatori
	     		
	     		/*-------------------------Amazon------------------------*/
     			
     			TableLayout tla = (TableLayout)  findViewById(R.id.tbl_txt1);
     			TextView amazonPrice = (TextView) findViewById(R.id.amazon_price);
	     		ImageView amazonImage = (ImageView) findViewById(R.id.amazon_image);
	     		
	     		System.out.println("linkAmazon " + linkAmazon);
	     		
	     		if ( linkAmazon.equals("") != true)
	     		{
	     			
		     	//	amazonImage.setVisibility(View.VISIBLE);
		     	//	amazonPrice.setVisibility(View.VISIBLE);
		     		/*
		     		TableLayout tla = (TableLayout)findViewById(R.id.tl_amazon);
		     		tla.setLayoutParams(new LayoutParams(width, LayoutParams.WRAP_CONTENT));
		     		*/
		     		//while (threadPrice == false);
	     			tla.setVisibility(View.VISIBLE);
	     			System.out.println("priceAmazon " + priceAmazon);		     		
		     		amazonPrice.setText(priceAmazon.toString() +" $");								// punem pretul
		     				     		
		     		amazonImage.setOnClickListener(new View.OnClickListener()
		             {				
		     			public void onClick(View v) 
		     			{
		     				//Setam link catre pagina de pe amazon
		     				
		     				Log.d(TAG, "onClick amazonImage din Product");
		     				Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(linkAmazon));
							startActivity(i);
		     						
		     				
		     			}
		     		});
	     		
	     		}
	     		else
	     		{
	     			tla.setVisibility(View.GONE);
	     			amazonImage.setVisibility(View.GONE);
		     		amazonPrice.setVisibility(View.GONE);
	     		}
	     		
	     		
	     		/*-------------------------eBay------------------------*/
	     		
	     		
	     		TableLayout tle = (TableLayout)  findViewById(R.id.tbl_txt2);
	     		TextView ebayPrice = (TextView) findViewById(R.id.ebay_price);
	     		ImageView ebayImage = (ImageView) findViewById(R.id.ebay_image);
	     		
	     		System.out.println(" linkEbay " +  linkEbay);
	     	
	     		if ( linkEbay.equals("") != true)
	     		{
		     		
	     	//		ebayPrice.setVisibility(View.VISIBLE);
	     	//		ebayImage.setVisibility(View.VISIBLE);
	     			
	     			/*
	     			TableLayout tle = (TableLayout)findViewById(R.id.tl_ebay);
		     		tle.setLayoutParams(new LayoutParams(width, LayoutParams.WRAP_CONTENT));
		     		*/
		     		//while (threadPrice == false);
		     			
	     			tle.setVisibility(View.VISIBLE);
	     			System.out.println("priceEbay " + priceEbay);
		     		ebayPrice.setText(priceEbay.toString() + " $");								// punem pretul
		     				     		
		     		ebayImage.setOnClickListener(new View.OnClickListener()
		             {				
		     			public void onClick(View v) 
		     			{
		     				//Setam link catre pagina de pe ebay
		     				
		     				Log.d(TAG, "onClick ebayImage din Product");
		     				
		     				Log.d(TAG, "onClick amazonImage din Product");
		     				Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(linkEbay));
							startActivity(i);
		     						
		     				
		     			}
		     		});
	     		     		
	     		}
	     		else
	     		{
	     			tle.setVisibility(View.GONE);
	     			ebayPrice.setVisibility(View.GONE);
	     			ebayImage.setVisibility(View.GONE);
	     		}
	     	
     		
     		}
     		catch(Exception e)
     		{
     			System.out.println("din showRetailers()" + e);
     		}
     		
     		
     	}
     	
     	
    
        
        
/*----------------------------------------------------   resize poza ------------------------------------------------- */
     	
	private Drawable resize(Drawable image, int scrWidth, int scrHeight, int imgHeight, int imgWeight) 
	{
		int imgH1, imgW1;
		double aux;
		// calculez noile dimensiuni
		// poza o sa ocupe 40% din ecran pe inaltime
		imgH1 = (int) (40 * scrHeight / 100);
		aux = imgH1 * 100 / imgHeight;
		imgW1 = (int) (imgWeight * aux / 100);
		Log.d ("scale", imgH1 + " " + imgW1);
		// scalez poza
	    Bitmap d = ((BitmapDrawable)image).getBitmap();
	    Bitmap bitmapOrig = Bitmap.createScaledBitmap(d, imgW1, imgH1, false);
	    
	   // TextView txtProduct = (TextView) findViewById(R.id.nameText1);
	  //  txtProduct.setText(imgW1 + " " + imgH1);
	    
	    return new BitmapDrawable(bitmapOrig);
	}
	
	private Drawable resize2(Drawable image, int scrWidth, int scrHeight, int imgHeight, int imgWeight) 
	{
		int imgH1, imgW1;
		double aux;
		// calculez noile dimensiuni
		// poza o sa ocupe 10% din ecran pe inaltime
		imgH1 = (int) (20 * scrHeight / 100);
		aux = imgH1 * 100 / imgHeight;
		imgW1 = (int) (imgWeight * aux / 100);
		Log.d ("scale", imgH1 + " " + imgW1);
		// scalez poza
	    Bitmap d = ((BitmapDrawable)image).getBitmap();
	    Bitmap bitmapOrig = Bitmap.createScaledBitmap(d, imgW1, imgH1, false);
	    
	   // TextView txtProduct = (TextView) findViewById(R.id.nameText1);
	  //  txtProduct.setText(imgW1 + " " + imgH1);
	    
	    return new BitmapDrawable(bitmapOrig);
	}
	
	
	/*       incarc poza din url        */
	public Drawable ImageOperations(Context ctx, String url, String saveFilename)
	{
        try {
            InputStream is = (InputStream) this.fetch(url);
            Drawable d = Drawable.createFromStream(is, "src");
            return d;
        } catch (MalformedURLException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
    }

    public Object fetch(String address) throws MalformedURLException,IOException {
        URL url = new URL(address);
        Object content = url.getContent();
        return content;
    }

	/*       end incarc poza din url        */
    
    
    /**** delogare ****/
	private void askOK()
	{
		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int which)
		    {
		        switch (which)
		        {
			        case DialogInterface.BUTTON_POSITIVE:
			        	delPref();
			        	gotoLogin();
			        	break;
	
			        case DialogInterface.BUTTON_NEGATIVE:
			            //No button clicked
			            break;
		        }
		    }
		};

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to logout?").setPositiveButton("Yes", dialogClickListener)
		    .setNegativeButton("No", dialogClickListener).show();
	}
	

	private void delPref ()
	{
    	// au nevoie de contextul aplicatiei deci nu le pot pune in clasa pentru delogare
    	SharedPreferences logPref = getSharedPreferences("LoginPref", MODE_PRIVATE);
    	SharedPreferences.Editor prefEditor = logPref.edit();
    	prefEditor.clear();
    	prefEditor.commit();
	}
	
	private void gotoLogin()
	{
		Intent intent = new Intent(getApplicationContext(), Login.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	
		finish();
	}
	/**** end delogare ****/
}
